package com.fate.system.utils;

import com.fate.system.enums.PictureSizeEnum;
import com.fate.system.vo.tencent.FormatImageVO;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

import static com.fate.system.enums.PictureSizeEnum.SIZE_6_INCH;

@Slf4j
public class PhotoLayoutGenerator {
  public static FormatImageVO generatePhotoLayout(String base64Image, PictureSizeEnum sizeEnum) {
    try {
      BufferedImage idPhoto = decodeBase64ToImage(base64Image);

      int paperWidth = SIZE_6_INCH.getWidthPx();
      int paperHeight = SIZE_6_INCH.getHeightPx();
      BufferedImage paper = new BufferedImage(paperWidth, paperHeight, BufferedImage.TYPE_INT_ARGB);

      int photoWidth = sizeEnum.getWidthPx();
      int photoHeight = sizeEnum.getHeightPx();

      Graphics2D g2d = paper.createGraphics();
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
      g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

      g2d.setColor(Color.WHITE);
      g2d.fillRect(0, 0, paperWidth, paperHeight);

      int rows, cols;
      cols =
          switch (sizeEnum) {
            case SIZE_1_INCH, SIZE_SMALL_1_INCH -> {
              rows = 3;
              yield 3;
            }
            case SIZE_LARGE_1_INCH, SIZE_2_INCH, SIZE_SMALL_2_INCH, SIZE_LARGE_2_INCH -> {
              rows = 2;
              yield 2;
            }
            case SIZE_3_INCH -> {
              rows = 1;
              yield 2;
            }
            case SIZE_4_INCH, SIZE_5_INCH, SIZE_6_INCH -> {
              rows = 1;
              yield 1;
            }
            default -> throw new IllegalArgumentException("Unsupported size.");
          };

      int xSpacing = (paperWidth - (photoWidth * cols)) / (cols + 1);
      int ySpacing = (paperHeight - (photoHeight * rows)) / (rows + 1);

      for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
          int x = xSpacing + col * (photoWidth + xSpacing);
          int y = ySpacing + row * (photoHeight + ySpacing);

          g2d.drawImage(idPhoto, x, y, photoWidth, photoHeight, null);
        }
      }

      g2d.dispose();

      return new FormatImageVO(
          null,
          null,
          null,
          encodeImageToBase64(paper),
          SIZE_6_INCH.getWidthPx(),
          SIZE_6_INCH.getHeightPx());
    } catch (Exception e) {
      log.error("生成照片布局异常", e);
      return null;
    }
  }

  private static BufferedImage decodeBase64ToImage(String base64Image) throws Exception {
    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
    BufferedImage image = ImageIO.read(bis);
    bis.close();
    return image;
  }

  private static String encodeImageToBase64(BufferedImage image) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos); // 使用PNG格式以确保无损压缩
    byte[] imageBytes = baos.toByteArray();
    baos.close();
    return Base64.getEncoder().encodeToString(imageBytes);
  }
}
